package com.cjlgb.design.oauth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cjlgb.design.common.core.constant.CacheName;
import com.cjlgb.design.common.mybatis.service.impl.BaseServiceImpl;
import com.cjlgb.design.oauth.entity.Oauth2ClientDetails;
import com.cjlgb.design.oauth.mapper.Oauth2ClientDetailsMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;


/**
 * @author WFT
 * @date 2019/5/19
 * description: 客户端详细配置接口
 */
@Service(value = "clientDetailsServiceImpl")
@CacheConfig(cacheNames = CacheName.OAUTH2_CLIENT_DETAILS)
public class ClientDetailsServiceImpl extends BaseServiceImpl<Oauth2ClientDetailsMapper,Oauth2ClientDetails>
        implements ClientDetailsService {

    @Override
    @Cacheable
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        Oauth2ClientDetails details = this.getOne(
                Wrappers.<Oauth2ClientDetails>lambdaQuery()
                        .eq(Oauth2ClientDetails::getClientId, clientId)
        );
        if (null == details){
            throw new ClientRegistrationException(clientId + "不存在");
        }
        if (-1 == details.getLockFlag()){
            throw new ClientRegistrationException(clientId + "被锁定");
        }
        /*
            客户端Id,资源Id,使用范围,授权方式,权限列表,回调用地址
         */
        BaseClientDetails clientDetails = new BaseClientDetails(
                clientId, null, details.getScope(),
                details.getAuthorizedTypes(), null,
                details.getRedirectUri()
        );
        //  密钥
        clientDetails.setClientSecret(details.getClientSecret());
        return clientDetails;
    }
}
